package com.atlin.project.utils.cds;

import com.atlin.project.contant.TrafficStatisticsConstant;
import com.atlin.project.utils.RedisUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class TrafficCounterUtils {

    @Resource
    private RedisUtils redisUtils;


    /**
     * 累加上传流量
     *
     * @param userKey 用户唯一标识（clientCode 或 userId）
     * @param bytes   上传流量字节数
     */
    public void addUploadTraffic(String userKey, long bytes) {
        if (userKey == null) {
            userKey = "unknown";
        }
        redisUtils.incrBy(TrafficStatisticsConstant.UPLOAD_KEY + userKey, bytes);
    }

    /**
     * 累加下载流量
     *
     * @param userKey 用户唯一标识（clientCode 或 userId）
     * @param bytes   下载流量字节数
     */
    public void addDownloadTraffic(String userKey, long bytes) {
        if (userKey == null) {
            userKey = "unknown";
        }
        redisUtils.incrBy(TrafficStatisticsConstant.DOWNLOAD_KEY + userKey, bytes);
    }

    /**
     * 获取某用户的上传流量
     */
    public long getUploadTraffic(String userKey) {
        Object value = redisUtils.get(TrafficStatisticsConstant.UPLOAD_KEY + userKey);
        return value == null ? 0L : Long.parseLong(value.toString());
    }

    /**
     * 获取某用户的下载流量
     */
    public long getDownloadTraffic(String userKey) {
        Object value = redisUtils.get(TrafficStatisticsConstant.DOWNLOAD_KEY + userKey);
        return value == null ? 0L : Long.parseLong(value.toString());
    }
}
